package com.iflytek.springboot_medicine.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
public class FileController {
    // 文件上传的目录路径，也就是项目的根路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    public ResponseMessage uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename(); // 获取文件名，例如：xxx.png

        // 创建目录（如果不存在）
        File directory = new File(filePath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs(); // 创建目录（包括父目录）
            if (!created) {
                return ResponseMessage.error("目录创建失败");
            }
        }
        //给文件名加一个唯一标识，防止文件名重复
        String fileName = System.currentTimeMillis()+"_"+ originalFilename;
        String realPath = filePath + fileName; //完整的文件路径
        // 保存文件
        try {
            // 使用 Files.write() 写入文件
            Path targetPath = Paths.get(realPath);
            Files.write(targetPath, file.getBytes());
            String url = "http://localhost:8080/files/download/"+fileName;
            return ResponseMessage.success("上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseMessage.error("文件上传失败");
        }
    }

    @RequestMapping("/download/{fileName}")
    public void domload(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        // 构建文件的完整路径
        String realPath = filePath + fileName;
        File file = new File(realPath);

        // 检查文件是否存在
        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404
            response.getWriter().write("文件未找到");
            return;
        }

        // 设置响应头
        response.setContentType("application/octet-stream"); // 二进制流
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8)); // 设置下载文件名

        // 读取文件并写入响应流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            //获取到文件的字节数组
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500
            response.getWriter().write("文件下载失败");
        }
    }
}
